package com.example.whereismystuff.views;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

import com.example.whereismystuff.R;
import com.example.whereismystuff.classes.ItemDataBaseAdapter;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class GoogleMapsView extends Activity {
	private GoogleMap googlemap;
	private LocationManager locMan;
	private Marker userMarker;
	
	private ItemDataBaseAdapter itemDataBaseAdapter;
	
	
	
	String itemName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.maps_layout);

		googlemap = ((MapFragment) getFragmentManager().findFragmentById(
				R.id.map)).getMap();
		Bundle extras = getIntent().getExtras();
		if(extras != null){
			if(extras.getString("ItemName") != null){
				itemName = extras.getString("ItemName");
			}
		}
		
		itemDataBaseAdapter=new ItemDataBaseAdapter(this);
		itemDataBaseAdapter=itemDataBaseAdapter.open();

		if (googlemap != null) {
			updatePlaces();
		}

		
	}

	public void updatePlaces() {
		
		locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		List<String> providers = locMan.getAllProviders();
		Criteria criteria = new Criteria();
		LatLng lastLatLng;
		String bestProvider;
		bestProvider = locMan.getBestProvider(criteria, false);
		Location lastLoc = locMan
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (lastLoc != null) {
			double lat = lastLoc.getLatitude();
			double lng = lastLoc.getLongitude();
			if(itemDataBaseAdapter.containsItem(itemName)){
				lat = Double.parseDouble(itemDataBaseAdapter.getSingleEntryLatitude(itemName));
				lng = Double.parseDouble(itemDataBaseAdapter.getSingleEntryLongitude(itemName));
				lastLatLng = new LatLng(lat, lng);
			} else {
				lastLatLng = new LatLng(lat, lng);
				if (userMarker != null)
					userMarker.remove();
				userMarker = googlemap.addMarker(new MarkerOptions().position(
						lastLatLng).title(itemName));
			}
			googlemap.moveCamera(CameraUpdateFactory.newLatLngZoom(lastLatLng, 15));
		}
		else {
			Toast.makeText(getApplicationContext(), "Location Could Not be Loaded", Toast.LENGTH_LONG).show();
		}
	}
}
